
package com.hlkj.pay.app.merchant.ext.impl.huifu.handler.params;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import cn.hutool.json.JSONObject;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.collection.CollectionUtils;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessContext;
import com.hlkj.pay.app.merchant.ext.impl.MerchantAccessFile;
import com.hlkj.pay.app.merchant.ext.impl.huifu.utils.HuiFuUtil;
import com.hlkj.pay.dto.merchant.MerchantAccessScene;
import com.hlkj.pay.dto.merchant.ProviderChannelFeeConfigList;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.enums.PayEnums;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessBusinessDO;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessCardDO;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessCertInfoDO;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessInfoDO;
import com.hlkj.pay.infrastructure.model.pay.PayChannelRequestDO;
import com.hlkj.pay.infrastructure.model.pay.PayWayDO;
import com.huifu.bspay.sdk.opps.core.request.V2MerchantBasicdataIndvRequest;
import com.huifu.bspay.sdk.opps.core.utils.DateTools;
import com.huifu.bspay.sdk.opps.core.utils.SequenceTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 汇付 商户进件参数处理
 * 
 * @author HlpayTeam
 * @date 2024/09/26 12:02
 */
@Slf4j
public class HuiFuMerchantAccessPersonParamsHandle extends HuiFuMerchantAccessCommonParamsHandle{

    /**
     * 企业商户进件-新增参数组装
     *
     * @param channelMerchantAccessContext
     * @return
     */
    public static V2MerchantBasicdataIndvRequest v2UserBasicdataIndvRequest(ChannelMerchantAccessContext channelMerchantAccessContext) {
        V2MerchantBasicdataIndvRequest request = new V2MerchantBasicdataIndvRequest();
        String reqSeqId32 = SequenceTools.getReqSeqId32();
        channelMerchantAccessContext.setReqSeqId(reqSeqId32);
        // 请求流水号
        request.setReqSeqId(reqSeqId32);
        // 请求日期
        request.setReqDate(DateTools.getCurrentDateYYYYMMDD());
        MerchantAccessInfoDO merchantAccessInfoDO = channelMerchantAccessContext.getMerchantAccessDto().getMerchantAccessInfo();
        MerchantAccessBusinessDO merchantAccessBusiness = channelMerchantAccessContext.getMerchantAccessDto()
                .getMerchantAccessBusiness();
        MerchantAccessCertInfoDO merchantAccessContact = channelMerchantAccessContext.getMerchantAccessDto()
                .getMerchantAccessContact();
        // ----- 商户信息-----
        // 企业用户名称
        request.setRegName(merchantAccessInfoDO.getName());
        // 联系人姓名
        request.setContactName(merchantAccessContact.getName());
        // 联系人手机号
        request.setContactMobileNo(merchantAccessContact.getPhone());
        // 联系人电子邮箱
        request.setContactEmail(merchantAccessContact.getOtherValue());
        // 经营省
        request.setProvId(merchantAccessBusiness.getProvinceCode());
        // 经营市
        request.setAreaId(merchantAccessBusiness.getCityCode());
        // 经营区
        request.setDistrictId(merchantAccessBusiness.getAreaCode());
        // 经营详细地址
        request.setDetailAddr(merchantAccessBusiness.getAddress());
        //卡号信息
        request.setCardInfo(getCardInfo(channelMerchantAccessContext.getMerchantAccessDto().getMerchantAccessCard()));
        // 设置非必填字段
        Map<String, Object> extendInfoMap = getExtendInfos(channelMerchantAccessContext);
        request.setExtendInfo(extendInfoMap);
        return request;
    }

    /**
     * 非必填字段
     * 
     * @return
     */
    private static Map<String, Object> getExtendInfos(ChannelMerchantAccessContext channelMerchantAccessContext) {
        // 设置非必填字段
        Map<String, Object> extendInfoMap = new HashMap<>();
        MerchantAccessInfoDO merchantAccessInfoDO = channelMerchantAccessContext.getMerchantAccessDto()
                .getMerchantAccessInfo();
        MerchantAccessCertInfoDO merchantAccessCertDO = channelMerchantAccessContext.getMerchantAccessDto()
                .getMerchantAccessLegal();
        MerchantAccessBusinessDO merchantAccessBusiness = channelMerchantAccessContext.getMerchantAccessDto()
                .getMerchantAccessBusiness();
        
        // 商户信息
        extendInfoMap.put("short_name", merchantAccessBusiness.getShortName());
        extendInfoMap.put("mcc", merchantAccessBusiness.getMcc());
        extendInfoMap.put("scene_type", sceneType(merchantAccessBusiness.getSceneType()));
        List<MerchantAccessScene> sceneList = merchantAccessBusiness.getSceneList();
        if (CollectionUtils.isNotEmpty(sceneList)) {
            List<MerchantAccessScene> webSceneList = sceneList.stream()
                    .filter(merchantAccessScene -> MerchantEnum.MERCHANT_SCENE_TYPE.WEB.getCode().equals(merchantAccessScene.getType())).collect(
                            Collectors.toList());
            if (CollectionUtils.isNotEmpty(sceneList)) {
                MerchantAccessScene merchantAccessSceneWeb = webSceneList.get(0);
                if (merchantAccessSceneWeb != null) {
                    extendInfoMap.put("mer_url", merchantAccessSceneWeb.getWebUrl());
                    extendInfoMap.put("mer_icp", merchantAccessSceneWeb.getIcp());
                }
            }
        }
        MerchantAccessFile merchantAccessFile=channelMerchantAccessContext.getMerchantAccessFile();
        // 经营信息
        // extendInfoMap.put("prov_id", merchantAccessSceneDO.getProvinceCode());
        // extendInfoMap.put("area_id", merchantAccessSceneDO.getCityCode());
        // extendInfoMap.put("district_id", merchantAccessSceneDO.getAreaCode());
        // extendInfoMap.put("detail_addr", merchantAccessSceneDO.getAddress());
        // 法人信息
        extendInfoMap.put("legal_cert_no", merchantAccessCertDO.getCertNo());
        extendInfoMap.put("legal_cert_begin_date", HuiFuUtil.date(merchantAccessCertDO.getCertBeginDate()));
        extendInfoMap.put("legal_cert_validity_type", merchantAccessCertDO.getCertValidityType().toString());
        extendInfoMap.put("legal_cert_end_date", HuiFuUtil.date(merchantAccessCertDO.getCertEndDate()));
        // extendInfoMap.put("legal_mobile_no", merchantAccessCertDO.getPhone());
        extendInfoMap.put("legal_addr", merchantAccessCertDO.getAddress());
        extendInfoMap.put("legal_cert_back_pic", merchantAccessFile.getLegalCertBackFileId());
        extendInfoMap.put("legal_cert_front_pic", merchantAccessFile.getLegalCertFrontFileId());
        //厂家信息
        extendInfoMap.put("store_header_pic", merchantAccessFile.getStoreHeaderFileId());
        extendInfoMap.put("store_indoor_pic", merchantAccessFile.getStoreIndoorFileId());
        extendInfoMap.put("store_cashier_desk_pic", merchantAccessFile.getStoreCashierDeskFileId());
        extendInfoMap.put("async_return_url", channelMerchantAccessContext.getAsyncReturnUrl());
        // 对私必填 卡正面
        extendInfoMap.put("settle_card_front_pic", merchantAccessFile.getSettleCardFrontFileId());
        if (channelMerchantAccessContext.getMerchantAccessDto().getMerchantAccessCard() != null) {
            // 结算卡信息配置
            // extendInfoMap.put("card_info", getCardInfo(channelMerchantAccessContext.getMerchantAccessCardDO()));
        }

        //结算配置
        extendInfoMap.put("settle_config", getSettleConfig(channelMerchantAccessContext.getMerchantFeeConfigList()));

        // 异步请求地址
        extendInfoMap.put("async_return_url", channelMerchantAccessContext.getAsyncReturnUrl());
        return extendInfoMap;
    }

    //进件
    public static String getSettleConfig(List<ProviderChannelFeeConfigList> merchantFeeConfigList) {
        JSONObject dto = new JSONObject();
        dto.set("settle_cycle", "D1");
        dto.set("fixed_ratio", "0.05");
        dto.set("constant_amt", "0.00");
        ProviderChannelFeeConfigList feeConfig = merchantFeeConfigList.stream()
                .filter(config -> Objects.equals(PayEnums.PAY_TYPE.FUNCTION.getCode(), config.getPayWayDO().getType())).findFirst().orElse(null);
        if (feeConfig != null) {
            PayWayDO payWayDO = feeConfig.getPayWayDO();
            if (MerchantEnum.SETTLE_CYCLE.T1.getPayWayCode().equals(payWayDO.getCode())) {
                dto.set("settle_cycle", "T1");
            }
            dto.set("fixed_ratio", feeConfig.getDefaultFeeConfigValue().getRateBase().toString());
            if (feeConfig.getDefaultFeeConfigValue().getFixedRate() != null) {
                DecimalFormat df = new DecimalFormat("#0.00");
                dto.set("constant_amt", df.format(feeConfig.getDefaultFeeConfigValue().getFixedRate()));
            }
        }
        return dto.toString();
    }


    // public static String sceneType(Integer sceneType) {
    //     PayEnums.SCENE_TYPE scene_type = PayEnums.SCENE_TYPE.from(sceneType);
    //     switch (scene_type) {
    //         case ONLINE:
    //             return "ONLINE";
    //         case OFFLINE:
    //             return "OFFLINE";
    //         default:
    //             return "ALL";
    //     }
    // }
    //
    // private static String getCardInfo(MerchantAccessCardDO merchantAccessCardDO) {
    //     JSONObject dto = new JSONObject();
    //     // 结算账户类型
    //     // dto.put("card_type", merchantAccessCardDO.getType());
    //     // 结算账户名
    //     dto.put("card_name", merchantAccessCardDO.getName());
    //     // 结算账号
    //     dto.put("card_no", merchantAccessCardDO.getCardNo());
    //     // 银行所在省
    //     dto.put("prov_id", merchantAccessCardDO.getProvinceCode());
    //     // 银行所在市
    //     dto.put("area_id", merchantAccessCardDO.getCityCode());
    //     // 银行编号参考： [银行编码](https://paas.huifu.com/partners/api/#/csfl/api_csfl_yhbm) ；
    //     // &lt;font color&#x3D;&quot;green&quot;&gt;示例值：01020000 &lt;/font&gt;
    //     // &lt;br/&gt;当card_type&#x3D;0时必填， 当card_type&#x3D;1或2时非必填
    //     dto.put("bank_code", merchantAccessCardDO.getBankCode());
    //     // 联行号参考：[银行支行编码](https://paas.huifu.com/partners/api/#/csfl/api_csfl_yhzhbm)
    //     // 当card_type&#x3D;0时必填， 当card_type&#x3D;1或2时非必填 &lt;br/&gt;&lt;font
    //     // color&#x3D;&quot;green&quot;&gt;示例值：102290026507&lt;/font&gt;
    //     // dto.put("branch_code", merchantAccessCardDO.getBranchCode());
    //     // 支行名称开户支行名称。 当card_type&#x3D;0时必填， 当card_type&#x3D;1或2时非必填；
    //     // &lt;br/&gt;&lt;font
    //     // color&#x3D;&quot;green&quot;&gt;示例值：中国工商银行上海市中山北路支行&lt;/font&gt;
    //     // dto.put("branch_name", merchantAccessCardDO.getName());
    //     // 持卡人证件类型参见《[自然人证件类型](https://paas.huifu.com/partners/api/#/api_ggcsbm?id&#x3D;%e8%87%aa%e7%84%b6%e4%ba%ba%e8%af%81%e4%bb%b6%e7%b1%bb%e5%9e%8b)》
    //     // 当card_type&#x3D;0时为空， 当card_type&#x3D;1或2时必填；&lt;font
    //     // color&#x3D;&quot;green&quot;&gt;示例值：00&lt;/font&gt;
    //     dto.put("cert_type", merchantAccessCardDO.getCertType());
    //     // 持卡人证件有效期截止日期日期格式：yyyyMMdd，以北京时间为准。&lt;font
    //     // color&#x3D;&quot;green&quot;&gt;示例值：20220125&lt;/font&gt;，当cert_validity_type&#x3D;0时必填；当cert_validity_type&#x3D;1时为空
    //     dto.put("cert_end_date", HuiFuUtil.date(merchantAccessCardDO.getCertEndDate()));
    //     // 持卡人证件号码
    //     dto.put("cert_no", merchantAccessCardDO.getCertNo());
    //     // 持卡人证件有效期类型
    //     dto.put("cert_validity_type", merchantAccessCardDO.getCertValidityType().toString());
    //     // 持卡人证件有效期开始
    //     dto.put("cert_begin_date", HuiFuUtil.date(merchantAccessCardDO.getCertBeginDate()));
    //     // 银行卡绑定手机号
    //     dto.put("mp", merchantAccessCardDO.getCardPhone());
    //
    //     return dto.toJSONString();
    // }
    
    

    /**
     * 新增文件参数转换
     * 
     * @param channelMerchantAccessContext
     */
    public static void addProcessFileId(ChannelMerchantAccessContext channelMerchantAccessContext) {
        MerchantAccessCertInfoDO merchantAccessCertDO = channelMerchantAccessContext.getMerchantAccessDto().getMerchantAccessLegal();
        MerchantAccessCardDO merchantAccessCardDO = channelMerchantAccessContext.getMerchantAccessDto().getMerchantAccessCard();
        MerchantAccessBusinessDO merchantAccessBusiness = channelMerchantAccessContext.getMerchantAccessDto()
                .getMerchantAccessBusiness();
        
        PayChannelRequestDO beforeMerchantAccessRequestDO = channelMerchantAccessContext.getBeforePayChannelRequestDO();

        Map<String, String> fileMap = new HashMap<>();
        if (beforeMerchantAccessRequestDO != null && StringUtils.hasText(beforeMerchantAccessRequestDO.getFileParams())) {
            fileMap = JsonUtils.parseObject(beforeMerchantAccessRequestDO.getFileParams(), Map.class);
        }
        MerchantAccessFile merchantAccessFile=new MerchantAccessFile();
        try {
            // 法人身份证人像面
            CommonResult<String> f02 = fileUploadProcess(fileMap, merchantAccessCertDO.getCertFrontUrl(), "法人身份证人像面","F40");
            if (f02.isSuccess()) {
                merchantAccessFile.setLegalCertFrontFileId(f02.getData());
            }
            else {
                channelMerchantAccessContext.setProcessStatus(Boolean.FALSE);
                channelMerchantAccessContext.setRemark(f02.getMsg());
            }
            // 法人身份证国徽面
            CommonResult<String> f03 = fileUploadProcess(fileMap, merchantAccessCertDO.getCertBackUrl(), "法人身份证国徽面","F41");
            if (f03.isSuccess()) {
                merchantAccessFile.setLegalCertBackFileId(f03.getData());
            }
            else {
                channelMerchantAccessContext.setProcessStatus(Boolean.FALSE);
                channelMerchantAccessContext.setRemark(f03.getMsg());
            }
            // 结算卡
            CommonResult<String> f13 = fileUploadProcess(fileMap, merchantAccessCardDO.getSettleCardFrontUrl(),"结算银行卡", "F13");
            if (f13.isSuccess()) {
                merchantAccessFile.setSettleCardFrontFileId(f13.getData());
            }
            else {
                channelMerchantAccessContext.setProcessStatus(Boolean.FALSE);
                channelMerchantAccessContext.setRemark(f13.getMsg());
            }
            // 线下经营-店铺门头照
            CommonResult<String> f22 = fileUploadProcess(fileMap, merchantAccessBusiness.getStoreHeaderUrl(), "门头照","F22");
            if (f22.isSuccess()) {
                merchantAccessFile.setStoreHeaderFileId(f22.getData());
            }
            else {
                channelMerchantAccessContext.setProcessStatus(Boolean.FALSE);
                channelMerchantAccessContext.setRemark(f22.getMsg());
            }
            // 线下经营-店铺内景/工作区域照
            CommonResult<String> f24 = fileUploadProcess(fileMap, merchantAccessBusiness.getStoreIndoorUrl(), "店铺内景照","F24");
            if (f24.isSuccess()) {
                merchantAccessFile.setStoreIndoorFileId(f24.getData());
            }
            else {
                channelMerchantAccessContext.setProcessStatus(Boolean.FALSE);
                channelMerchantAccessContext.setRemark(f24.getMsg());
            }
            // 线下经营-店铺内景/工作区域照
            CommonResult<String> f105 = fileUploadProcess(fileMap, merchantAccessBusiness.getStoreCashierDeskUrl(),"收银台", "F105");
            if (f105.isSuccess()) {
                merchantAccessFile.setStoreCashierDeskFileId(f105.getData());
            }
            else {
                channelMerchantAccessContext.setProcessStatus(Boolean.FALSE);
                channelMerchantAccessContext.setRemark(f105.getMsg());
            }
            channelMerchantAccessContext.setMerchantAccessFile(merchantAccessFile);
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        finally {
            PayChannelRequestDO payChannelRequestDO = channelMerchantAccessContext.getPayChannelRequestDO();
            payChannelRequestDO.setFileParams(JsonUtils.toJsonString(fileMap));
        }
    }

    // public static CommonResult<String> fileUploadProcess(Map<String, String> fileMap, String fileUrl, String fileType) {
    //     if (!StringUtils.hasText(fileUrl)) {
    //         return CommonResult.success();
    //     }
    //     String fileKey = fileUrl.hashCode() + fileType;
    //     String fileId = fileMap.get(fileKey);
    //     if (StringUtils.hasText(fileId)) {
    //         log.info("汇付文件映射获取成功 fileUrl:{},fileId:{}", fileUrl, fileId);
    //         return CommonResult.success(fileId);
    //     }
    //     log.info("汇付文件映射获取未成功 fileType:{}, fileUrl:{}", fileType, fileUrl);
    //     CommonResult<String> f371 = HuiFuUtil.fileUpload(fileUrl, fileType);
    //     if (f371.isSuccess()) {
    //         fileMap.put(fileKey, f371.getData());
    //     }
    //     return f371;
    // }

}
